package com.zookeeper.case1;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author WangGuoLiang
 * @program ZooKeeper
 * @description 客户端连接zookeeper
 * @create 2021-09-05 00:49
 **/
public class DistributeClient {
    ZooKeeper zooKeeper;
    public static void main(String[] args) throws IOException, KeeperException, InterruptedException {
        DistributeClient distributeClient = new DistributeClient();
        //1 连接zookeeper
        distributeClient.getZk();
        //2 监听指定"/Servers"节点
        distributeClient.getServer();
        //3 业务逻辑处理
        distributeClient.business();
    }

    private void business() throws InterruptedException {
        Thread.sleep(Long.MAX_VALUE);
    }

    private void getServer() throws KeeperException, InterruptedException {
        List<String> children = zooKeeper.getChildren("/servers", true);
        List<String> list = new ArrayList<>();
        for (String child : children) {
            byte[] data = zooKeeper.getData("/servers/" + child, false, null);
            list.add(new String(data));

        }
        System.out.println(list);

    }

    private void getZk() throws IOException {
        zooKeeper = new ZooKeeper("47.106.199.16:2181", 2000, new Watcher() {
            @Override
            public void process(WatchedEvent watchedEvent) {
                try {
                    //使得客户端可以一直监听
                    getServer();
                } catch (KeeperException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}

